// accounting/income_statement/income_statement.js
let listBehavior = require('../../behavior/list');

let nowYear = new Date().getFullYear(),
  nowMonth = new Date().getMonth() + 1;
nowMonth = nowMonth > 9 ? nowMonth : '0'+nowMonth;
let defPeriod = nowYear + '' + nowMonth;
Page({
  behaviors: [ listBehavior, ],

  /**
   * 页面的初始数据
   */
  data: {
    quickFlag: false,
    account_period: defPeriod,


    searchSlotFlag: false,

    //搜索--利润表
    searchList: [
      {field_id: 'account_period',field_name: '会计期',dfltVal: defPeriod,type: 'reference1', optionList: [],optionId: 'account_period',optionName: 'account_period'},
      { field_id: 'assist',field_name: '辅助类别',type: 'reference1', optionList: [],optionId: 'row_id',optionName: 'assist_account'},
    ],
    //搜索核算项目
    assistSearch: [{ field_id: 'assist_project',field_name: '核算项目',type: 'multiple', optionList: [],optionId: 'id',optionName: 'name'}],
    assistSearchObj: {  //搜索内容
      all_assist_account_row_id: '',  //辅助类别行id
      quantity_account_row_id_list: '', //核算项目行id
      is_open_last_year: false, //显示上年同期
      is_open_this_year: true, //显示本年累计
      showMonth: true //显示本期金额
    },
    //利润表核算项目数据
    assistData: [],
    //动态显示核算项目
    assistCol: [],
    //利润表核算项目过滤--全部、一级
    assistNav: 'assistAll',

    assistFlag: false,   //显示辅助核算
    assistName:'',    //头部辅助核算显示名称
    is_open_last_year: false, //显示上年同期
    is_open_this_year: true, //显示本年累计
    showMonth: true, //显示本期金额
    hideBlank: false, //隐藏空白

    emptyFlag: true,   //空数据

    //利润表数据
    incomeData: [],
    //补充数据
    balanceData: [],
    activeTable: '1002'
  },
  //显示搜索
  showQuick(){
    this.setData({
      quickFlag: !this.data.quickFlag,
    })
  },
  //切换导航栏
  toggleNav(e){
    let tid = e.currentTarget.dataset.tid,
      obj = {};
    if (['1001','1002'].includes(tid)) {
      obj.activeTable = tid;
    }else {
      obj.assistNav = tid;
    }
    this.setData(obj);
  },
  //修改查询条件
  searchChange(e){
    let {field_id,val} = e.detail,
      obj = {},
      {assistSearchObj} = this.data;

    if (field_id === 'assist'){  //辅助核算
      this.setData({
        [`assistSearchObj.all_assist_account_row_id`]: val
      });
      val && this.getAssistOptions();
    }
    if (field_id === 'account_period') {  //会计期
      if (!val) { wx.$toast('请选择会计期');return}
      this.setData({
        [`account_period`]: val
      });
      assistSearchObj.all_assist_account_row_id && this.getAssistOptions();
    }
    if (field_id === 'assist_project') {  //核算项目
      this.setData({
        [`assistSearchObj.quantity_account_row_id_list`]: val && val.join(',')
      })
    }
  },
  //重置搜索条件
  searchReset(){
    this.setData({
      [`assistSearchObj.all_assist_account_row_id`]: ''
    });
  },
  //切换辅助核算搜索条件复选框
  onCheckChange(e){
    let {field} = e.currentTarget.dataset;
    this.setData({
      [`assistSearchObj.${field}`]: !this.data.assistSearchObj[field]
    })
  },
  //隐藏空白
  onHideBlank(e){
    this.setData({hideBlank: !this.data.hideBlank});
  },
  //搜索数据
  searchData({detail}){
    let {assistSearchObj,searchList,account_period} = this.data;

    if (assistSearchObj.all_assist_account_row_id) {
      //获取辅助类别名称
      let as = searchList[1].optionList.find(item=>{
        return item.row_id == assistSearchObj.all_assist_account_row_id;
      });
      let {is_open_last_year,is_open_this_year,showMonth} = assistSearchObj;
      let obj = {
        is_open_last_year,is_open_this_year,showMonth,
        assistFlag: true,
        assistName: as.assist_account,
        emptyFlag: true,
      };
      this.setData(obj);
      this.sumReport(account_period).then(()=>{
        this.getAssistData();
      });
    }else {
      let obj = {
        emptyFlag: true,
        assistFlag: false,
      };
      wx.$each(detail,(i,item)=>{
        if (item.CompareWith === 'account_period') {
          obj.account_period = item.CompareValue
        }
      });
      this.setData(obj);
      this.sumReport(account_period).then(()=>{
        this.getData(1002);
        this.getData(1001);
      });
    }
  },

  getData(tid){
    let {account_period,activeTable} = this.data;
    wx.$post(3,'CustomAccountContent/query_custom_account_content',{oby: "project_id", account_period: account_period, table_id: tid}).then(res=>{
      if (res.errcode != 0)return;
      let data = res.data.row || [],
        list = [],obj = {};
      if (tid == 1002){ //利润表
        wx.$each(data,(i,item)=>{
          if (item.data_level != 2){
            item.children = [];
            list.push(item)
          } else {
            list[list.length-1].children.push(item)
          }
        });
        obj = {
          incomeData: list
        };
        activeTable === '1002' && (obj[`displayObj.empty`] = list.length === 0)
        this.setData(obj);

      }else {
        //资产负债表-补充财务情况
        let project = ['货币资金','应收账款','存货','应付账款'];
        wx.$each(data,(i,item)=>{
          if (project.indexOf(item.project_name.trim()) >=0){
            list.push(item)
          }
        });
        obj = {balanceData: list};
      }
      activeTable == tid && (obj.emptyFlag = list.length === 0)
      this.setData(obj);
    })
  },

  //统计报表
  sumReport(period){
    let url1 = 'Voucher/sum_all_voucher',
      url2 = 'CustomAccount/update_auto_value',
      post = {"account_period":period };
    return new Promise(resolve => {
      wx.showLoading();
      wx.$post(3,url1,post,false).then(res=>{
        if (res.errcode != 0){
          wx.$toast('统计凭证失败');
          return;
        }
        wx.$post(3,url2,post,false).then(res=>{
          wx.hideLoading();
          if (res.errcode != 0){
            wx.$toast('统计报表失败');
            return;
          }
          resolve();
        })
      })
    })
  },

  //获取辅助核算数据
  getAssistData(){
    let {account_period,assistSearchObj} = this.data,
      {all_assist_account_row_id,quantity_account_row_id_list,is_open_last_year,is_open_this_year} = assistSearchObj,
      post = {
        account_period_s: account_period,
        account_period_e: account_period,
        all_assist_account_row_id,quantity_account_row_id_list,is_open_last_year,is_open_this_year
      };
    wx.$post(1,'AllAssistAccount/query_project_income_statement',post).then(res=>{
      if (res.errcode != 0)return;
      let data = res.data.row || [],
        list = [];
      //计算合计
      wx.$each(data,(i,item)=>{
        let auto_value_total = 0,
          this_year_auto_value_total = 0,
          last_year_auto_value_total = 0;

        wx.$each(item,function (key,val) {
          if (key.indexOf('auto_value_') === 0){
            auto_value_total += parseFloat(val);
          }
          if (key.indexOf('this_year_auto_value_') === 0){
            this_year_auto_value_total += parseFloat(val);
          }
          if (key.indexOf('last_year_auto_value_') === 0){
            last_year_auto_value_total += parseFloat(val);
          }
        });
        item.auto_value_total = parseFloat(auto_value_total.toFixed(2));
        item.this_year_auto_value_total = parseFloat(this_year_auto_value_total.toFixed(2));
        item.last_year_auto_value_total = parseFloat(last_year_auto_value_total.toFixed(2));

      });

      //获取辅助核算项目字段
      let nameArr = [],
        fieldList = [];
      wx.$each(res.data.sum,(i,item)=>{
        let reg = /^auto_value_.*/;       //以auto_value_开头的
        // if (arr && arr[1]){
        if (reg.test(item.field_id)){
          let arr = item.field_name && item.field_name.split('|');
          let name = arr[0],
            // index = nameArr.indexOf(name),
            fieldId = item.field_id,
            id = fieldId.substring(fieldId.lastIndexOf('_')+1);
          fieldList.push({name,id});
          /*if (index < 0){
            nameArr.push(name);
          }*/
        }
      });
      fieldList.push({id: 'total', name: '合计'});


      this.setData({assistData: data,emptyFlag: data.length === 0,assistCol: fieldList});
    })
  },

  //获取核算项目
  getAssistOptions(rid){
    let {account_period,assistSearchObj} = this.data,
      post = {
      "all_assist_account_row_id": assistSearchObj.all_assist_account_row_id,
      "account_period_s": account_period,
      "account_period_e": account_period,
      "account_level_s": 0,
      "account_level_e": 0,
    }
    wx.$post(1,'AllAssistAccount/query_assist_account_list',post).then(res=>{
      if (res.errcode != 0)return;
      let data = res.data.row || [],
        list = [],ids = [];
      wx.$each(data,(i,item)=>{
        let obj = {
          id: item.data_id,
          name: item.data_id + ' ' + item.data_value
        };
        if (!list.some(function (it1) {
          return it1.id === obj.id;
        })) {
          list.push(obj);
          ids.push(item.data_id);
        }
      });
      this.setData({
        [`assistSearch[0].optionList`]: list,
        [`assistSearchObj.quantity_account_row_id_list`]: ids.join(',')
      });
    })
  },

  //获取下拉数据
  getOptionsList (arg){
    let [key,v,url,post] = arg;
    return new Promise((resolve,reject) => {
      wx.$post(v, url, post).then(res=>{
        if (res.errcode != 0){
          reject();
          return;
        }
        let data = res.data.row || [],
          list = data;
        resolve({[key]: list});
      });
    });
  },
  ready(){

    let parmaArr = [
        ['assist',1,'AllAssistAccount/select_all_assist_account',{}],  //辅助核算
        ['account_period',3,'Account/query_all_account_period',{"limit":0,"page":1}],  //会计期
      ],
      pmArr = [];
    wx.$each(parmaArr,(i,item)=>{
      pmArr.push(this.getOptionsList(item));
    });
    Promise.all(pmArr.map(p => p.catch(err => ''))).then(res=>{
      let resObj = {};
      wx.$each(res,(i,item)=>{
        resObj = {...resObj,...item}
      });
      let searchList = this.data.searchList;
      wx.$each(searchList,(i,item)=>{
        if (resObj[item.field_id]){
          item.optionList = resObj[item.field_id];
        }
      });
      console.log(searchList);
      this.setData({searchList})
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    this.sumReport(defPeriod).then(()=>{
      this.getData(1002);
      this.getData(1001);
    });
    this.ready();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
